<template>
  <div class="my-tag">
    <input v-if="isEdit" v-focus :value="value" class="input" type="text" placeholder="输入标签" @blur="onBlur"
      @keyup.enter="onSubmit" />
    <div v-else class="text" @dblclick="onDblclick">{{ value }}</div>
  </div>
</template>

<script>
export default {
  name: 'MyTag',

  props: {
    value: String
  },
  data() {
    return {
      isEdit: false
    }
  },

  directives: {
    focus: {
      inserted(el) {
        el.focus();
      }
    }
  },

  methods: {

    // 1. 双击
    onDblclick() {
      this.isEdit = true;
    },

    // 2. 输入框失去焦点
    onBlur() {
      this.isEdit = false;
    },

    // 3. 输入框回车
    onSubmit(e) {
      // 3.1 判断输入框是否为空
      if (e.target.value.trim() === '') {
        alert('标签内容不能为空');
        return;
      }

      // 3.2 把标签内容回传父组件
      this.$emit('input', e.target.value.trim());

      // 3.3 隐藏输入框
      this.isEdit = false;
    }
  }
}
</script>

<style scoped lang="less">
.my-tag {
  cursor: pointer;

  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;

    &::placeholder {
      color: #666;
    }
  }
}
</style>